package com.simplehire.controller;

import com.simplehire.model.User;
import com.simplehire.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequiredArgsConstructor
public class AuthController {

    private final UserService userService;
    private final PasswordEncoder passwordEncoder;

    // 登录页面
    @GetMapping("/login")
    public String showLoginPage() {
        return "login";
    }

    // 注册页面
    @GetMapping("/register")
    public String showRegisterPage() {
        return "register";
    }

    // 处理注册表单提交
    @PostMapping("/register")
    public String registerUser(
            @RequestParam String username,
            @RequestParam String password,
            @RequestParam String confirmPassword,
            RedirectAttributes redirectAttributes,
            Model model
    ) {
        // 基本验证
        if (!password.equals(confirmPassword)) {
            model.addAttribute("error", "密码不一致");
            return "register";
        }

        try {
            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(password); // 会在Service中加密
            newUser.setRole(User.Role.USER);

            userService.createUser(newUser);

            redirectAttributes.addFlashAttribute("success", "注册成功，请登录");
            return "redirect:/login";
        } catch (RuntimeException e) {
            model.addAttribute("error", e.getMessage());
            return "register";
        }
    }

    // 首页
    @GetMapping("/")
    public String showHomePage() {
        return "home";
    }
}